# -*- coding:utf-8 -*-
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None
class Solution:
    # def EntryNodeOfLoop(self, pHead):
    #     # write code here
    #     if not pHead:
    #         return None
    #     nums= self.loop_nums(pHead)
    #     if nums==-1:
    #         return None
    #     f = l = pHead
    #     while nums>0:
    #         f= f.next
    #         nums-=1
    #     while f!=l:
    #         f = f.next
    #         l = l.next
    #     return l
    # def loop_nums(self,pHead):
    #     l =  pHead
    #     f = pHead.next
    #     while f and f.next:
    #         if l==f:
    #             l = l.next
    #             count = 1
    #             while l!=f:
    #                 l = l.next
    #                 count+=1
    #             return count
    #         l = l.next
    #         f = f.next.next
    #     return -1

    def EntryNodeOfLoop(self, p):
        # write code here
        if not p:
            return None
        c = 1
        l = p
        f = p.next
        while f and f.next:
            f = f.next.next
            l = l.next
            if f == l:
                f = p
                while f != l:
                    f = f.next
                    l = l.next
                return f
        return None


node1 = ListNode(1)
node2 = ListNode(2)
node3 = ListNode(3)
node4 = ListNode(4)
node5 = ListNode(5)
node6 = ListNode(6)

node1.next = node2
node2.next = node3
node3.next = node4
node4.next = node5
node5.next = node6
node6.next = node3

s = Solution()
m = s.EntryNodeOfLoop(node1)
print(m)



